#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import re
import random
import string
import time
import hashlib
import copy
from urllib import parse
from datetime import datetime
from datetime import timedelta

# 预留了下载状态，但是没有用上
run_status = {
    'quit': -3,
    'pause': -2,
    'fail': -1,
    'success': 0,
    'duplicate': 1,
    'except': 2
}


def random_str(min_len, max_len):
    if min_len >= max_len:
        salt = ''.join(random.sample(string.ascii_letters + string.digits, max_len))
    else:
        length = random.randint(min_len, max_len)
        salt = ''.join(random.sample(string.ascii_letters + string.digits, length))
    return salt


def md5(target=None):
    if target is None:
        time_stamp = time.time()
        target = '{0}'.format(time_stamp)
    md5_obj = hashlib.md5()
    md5_obj.update(target.encode())
    return md5_obj.hexdigest()


def get_url_params(url):
    return parse.parse_qs(parse.urlparse(url).query)


# 顺序消费 有限资源，如proxy 如cookie
def get_next_value(rds, idx_key, hash_key, lock_prifix, lock_sec, lock_step=3, max_limit=180):
    cur_index = rds.incr(idx_key)
    num = rds.hlen(hash_key)
    if num == 0:
        return None
    field = cur_index % num
    value = rds.hget(hash_key, field)
    if lock_sec > 0:
        lock_key = '{0}_{1}'.format(lock_prifix, value)
        # 随机时间区间，最小lock_sec
        min_sec = lock_sec + field * lock_step
        max_sec = lock_sec + (field + 1) * lock_step
        max_sec = max_sec if max_sec < max_limit else max_limit
        min_sec = min_sec if min_sec < max_sec else max_sec - 3
        rand_sec = random.randint(min_sec, max_sec)
        # 尝试锁定直至成功
        while True:
            cur_tm = time.strftime('%Y%m%d%H%M%S')
            res = rds.set(lock_key, cur_tm, ex=rand_sec, nx=True)
            if res is None:
                time.sleep(0.5)
            else:
                return value
    return value


def set_two_key(src_dic, k1, k2, dest_dic):
    if k1 in src_dic and len(src_dic[k1]) > 0:
        dest_dic[k2] = src_dic[k1]
    elif k2 in src_dic and len(src_dic[k2]) > 0:
        dest_dic[k2] = src_dic[k2]


def check_kv(js, k):
    if k in js:
        if isinstance(js[k], int) and js[k] is not None:
            if len(js[k]) > 0:
                return js[k]
    return None


def get_info(info_dic, keys):
    info = {}
    for k in keys:
        value = check_kv(info_dic, k)
        if value is not None:
            info[k] = value


def random_ua():
    num = random.randint(1000, 9999)
    user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 ' \
                 '(KHTML, like Gecko) Chrome/70.0.{0}.77 Safari/537.36'.format(num)
    return user_agent


def trim_json(task, src):
    dest = {'task': copy.deepcopy(task)}
    for key, value in src.items():
        if is_none(value):
            continue
        dest[key] = value
    return dest


def get_url(url_prefix, params):
    query_string = parse.urlencode(params)
    return '{0}?{1}'.format(url_prefix, query_string)


def is_none(s):
    if s is None:
        return True
    flag = False
    if isinstance(s, str):
        if len(s.strip()) == 0:
            flag = True
        if s == '-':
            flag = True
    elif isinstance(s, list):
        if len(s) == 0:
            flag = True
    elif isinstance(s, dict):
        flag = True
        for v in s.values():
            if is_none(v):
                continue
            flag = False
            break
    return flag


def get_name_by_url(url, split_char='.'):
    last_name = url.split('/')[-1]
    r_pos = last_name.rfind(split_char)
    return last_name[:r_pos]


def str_to_num(target):
    num = 0
    try:
        num = int(target)
    except Exception as e:
        print(e)
    return num


def is_all_zh(s):
    """全部为汉字的返回TRUE"""
    for c in s:
        if '\u4e00' <= c <= '\u9fa5':
            return True
    return False


# target_str '<span class="stag"> <a target="_blank"
# href="http://www.canyin88.com/plus/search.php?kwtype=0&q=%CD%E2%C2%F4&searchtype=titlekeyword"> 外卖 </a> </span>
# <span class="stag"> <a target="_blank" href="http://www.canyin88.com/plus/search.php?kwtype=0&q=%CD%E2%C2%F4%C6%EF
# %CA%D6&searchtype=titlekeyword"> 外卖骑手 </a> </span>'
#
# return 外卖,外卖骑手
def remove_html_label(target_str, split_char=','):
    r_str = re.sub("<[^>]*?>", ' ', target_str).strip()
    return re.sub(' +', split_char, r_str)


def aihehuo_quote(page, per=10):
    pre = parse.quote('{"page"')
    mid = parse.quote('"per"')
    end = parse.quote('}')
    return '{}:{},{}:{}{}'.format(pre, page, mid, per, end)


def get_date_time(time_str):
    nums = re.findall(r'\d+', time_str)
    cur_time = datetime.now()
    f_time = None
    if len(nums) > 0:
        num = int(nums[0])
        if time_str.find('天') > 0:
            pre_time = cur_time - timedelta(days=num)
            f_time = pre_time.strftime('%Y-%m-%d 00:00:00')
        elif time_str.find('小时') > 0:
            pre_time = cur_time - timedelta(hours=num)
            f_time = pre_time.strftime('%Y-%m-%d %H:00:00')
        elif time_str.find('分钟') > 0:
            pre_time = cur_time - timedelta(minutes=num)
            f_time = pre_time.strftime('%Y-%m-%d %H:%M:00')
        elif time_str.find('秒') > 0:
            pre_time = cur_time - timedelta(seconds=num)
            f_time = pre_time.strftime('%Y-%m-%d %H:%M:%S')
    if f_time is None:
        f_time = cur_time.strftime('%Y-%m-%d %H:%M:%S')
    return f_time


def remove_emoji(desstr, restr=''):
    # 过滤表情
    try:
        res = re.compile(u'[\U00010000-\U0010ffff]')
    except re.error:
        res = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
    return res.sub(restr, desstr)
